package com.example.goodpet.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.goodpet.R;
import com.example.goodpet.bean.LoginData;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.UIUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseEditTextUtils;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class LoginActivity extends FragmentActivity implements TextWatcher, CompoundButton.OnCheckedChangeListener {
    String TAG=this.getClass().getSimpleName();
    //final
    public static final int VERIFICATION_STATE=100;
    private EditText etPhoneNumber;
    private EditText etPassword;
    private Button btnLogin;
    private TextView register;
    private CheckBox cbSelect;
    private TextView tvAgreement;

    private String phoneNumber;
    private String password;

    private Drawable clear;
    private Drawable eyeOpen;
    private Drawable eyeClose;
    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        etPhoneNumber=findViewById(R.id.etPhoneNumber);
        etPassword=findViewById(R.id.etPassword);
        btnLogin=findViewById(R.id.btnLogin);
        register=findViewById(R.id.register);
        cbSelect = findViewById(R.id.cb_select);
        tvAgreement = findViewById(R.id.tv_agreement);
        mContext=this;

        initListener();
        
        initDate();
        //testImage();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: "+this.getTaskId());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityManager.getInstance().removeCurrent();
    }

    private void initDate() {
        eyeClose = getResources().getDrawable(R.drawable.d_pwd_hide);
        eyeOpen = getResources().getDrawable(R.drawable.d_pwd_show);
        clear = getResources().getDrawable(R.drawable.d_clear);

        tvAgreement.setText(getSpannable());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        EaseEditTextUtils.changePwdDrawableRight(etPassword, eyeClose, eyeOpen, null, null, null);
    }

    private void initListener() {
        etPassword.addTextChangedListener(this);
        etPhoneNumber.addTextChangedListener(this);
        cbSelect.setOnCheckedChangeListener(this);
        EaseEditTextUtils.clearEditTextListener(etPhoneNumber);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(LoginActivity.this, ShowVerificationActivity.class), VERIFICATION_STATE);
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });
    }

    private void loginIMUser() {
        EMClient.getInstance().login(SecurityUtils.encryptPhoneNumber(phoneNumber),password,new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d("main", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("main", "登录聊天服务器失败！");
            }
        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        checkEditContent();
    }
    private void checkEditContent() {
        phoneNumber = etPhoneNumber.getText().toString().trim();
        password = SecurityUtils.MD5(etPassword.getText().toString().trim());
        EaseEditTextUtils.showRightDrawable(etPhoneNumber, clear);
        EaseEditTextUtils.showRightDrawable(etPassword, eyeClose);
        setButtonEnable(!TextUtils.isEmpty(phoneNumber) && !TextUtils.isEmpty(password) && phoneNumber.length()==11 && cbSelect.isChecked()  );
    }
    private void setButtonEnable(boolean enable) {
        btnLogin.setEnabled(enable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            //发送登录请求
            if (requestCode==VERIFICATION_STATE){
                Retrofit retrofit = RetrofitSingleton.getRetrofitNetConfig();
                UserService userService = retrofit.create(UserService.class);
                userService.login(phoneNumber,password).enqueue(new Callback<LoginData>() {
                    @Override
                    public void onResponse(Call<LoginData> call, Response<LoginData> response) {
                        LoginData body = response.body();
                        if (body.isSuccess()){
                            MyApplication.saveAccount(body.getData());
                            loginIMUser();
                            setResult(RESULT_OK);
                            ActivityManager.getInstance().removeCurrent();
                            //Intent intent = new Intent(UIUtils.getContext(), MainActivity.class);
                            //startActivity(intent);
                        }else {
                            UIUtils.toast("用户名或密码错误",false);
                        }
                    }

                    @Override
                    public void onFailure(Call<LoginData> call, Throwable t) {
                        t.printStackTrace();
                        UIUtils.toast("网络通信失败",false);
                    }
                });

            }

        }
        }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId()==R.id.cb_select){
            setButtonEnable(!TextUtils.isEmpty(phoneNumber) && !TextUtils.isEmpty(password) && phoneNumber.length()==11  && isChecked);
        }
    }
    private SpannableString getSpannable() {
        SpannableString spanStr = new SpannableString(getString(R.string.em_login_agreement));
        //设置下划线
        //spanStr.setSpan(new UnderlineSpan(), 3, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanStr.setSpan(new LoginActivity.MyClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                WebViewActivity.actionStart(mContext, Constants.BASE_URL_support+"/agreement.html");
            }
        }, 2, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        //spanStr.setSpan(new UnderlineSpan(), 10, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanStr.setSpan(new LoginActivity.MyClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                WebViewActivity.actionStart(mContext, Constants.BASE_URL_support+"/privacy.html");
            }
        }, 8, spanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanStr;
    }

    private abstract class MyClickableSpan extends ClickableSpan {

        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            ds.bgColor = Color.TRANSPARENT;
            ds.setColor(ContextCompat.getColor(mContext, R.color.black));
        }
    }
}